import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { userApi } from "@/api";

export const useUserStore = defineStore("user", () => {
  // 状态
  const token = ref(getToken() || "");
  const userInfo = ref({
    country: "",
    nickname: "",
    user_name: "",
    user_code: "",
    user_avatar: "",
    invitation_code: "",
    real_name_status: "", // 0未认证 1 审核中 2已认证 3审核失败
    phone: "",
    email: "",
  });

  const isLoggedIn = computed(() => {
    const hasToken = !!token.value;
    return hasToken;
  });

  // 用户状态-是否已认证
  const isAuthentication = computed(() => {
    return userInfo.value.real_name_status === 2;
  });

  // 登录
  const login = async (loginData) => {
    try {
      const params = { ...loginData };
      const response = await userApi.loginApi(params);
      if (response.code === 0) {
        // 保存token到本地存储和状态管理
        const accessToken = response.data.access_token;
        setToken(accessToken);
        token.value = accessToken;
        return response;
      }
    } catch (error) {
      return error;
    }
  };

  // 短信验证码登录
  const loginWithSms = async (smsData) => {
    try {
      const params = {
        phone: smsData?.phone,
        code: smsData?.code,
        country: smsData?.country, // 可选
        invitation_code: smsData?.invitationCode, // 可选
      };
      const response = await userApi.loginCodeApi(params);
      if (response.code === 0) {
        // 保存token到本地存储和状态管理
        const accessToken = response.data.access_token;
        setToken(accessToken);
        token.value = accessToken;
      }
      return response;
    } catch (error) {
      return error;
    }
  };

  // 注册
  const register = async (registerData) => {
    /**
     *"user_name":"",
      "phone":"2",  // user_name和phone 至少一个
      "nickname":"hhk", // 可选
      "password":"123456",
      "repeat_password":"123456",
      "country":"China",
      "invitation_code":"123321123"  // 可选
     */
    try {
      const params = { ...registerData };
      const response = await userApi.registerApi(params);
      if (response.code === 0) {
        // 保存token到本地存储和状态管理
        const accessToken = response.data.access_token;
        setToken(accessToken);
        token.value = accessToken;
        return response;
      }
    } catch (error) {
      return error;
    }
  };

  // 发送短信验证码
  const sendSmsCode = async (phoneData) => {
    try {
      const params = {
        phone: phoneData?.phone,
        country_code: phoneData?.countryCode,
        type: phoneData?.type || 1, // 1|登录 2|绑定手机 3|绑定邮箱
      };
      const response = await userApi.getCodeApi(params);
      return response;
    } catch (error) {
      return error;
    }
  };

  // 获取用户信息
  const getUserInfo = async () => {
    const currentToken = getToken();
    if (!currentToken) {
      return { success: false, message: "用户未登录" };
    }
    try {
      const response = await userApi.getUserInfoApi();
      if (response.code === 0) {
        userInfo.value = response.data;
        // 保存用户信息到本地存储
        uni.setStorageSync("userInfo", response.data);
        return response;
      }
      return response;
    } catch (error) {
      return error;
    }
  };

  // 编辑用户信息
  const editUserInfo = async (userData) => {
    const params = {
      nickname: userData?.nickname, // 昵称 可选
      user_avatar: userData?.user_avatar, //头像 可选
    };
    try {
      const response = await userApi.editUserInfoApi(params);
      if (response.code === 0) {
        getUserInfo();
        return response;
      }
      return response;
    } catch (error) {
      return error;
    }
  };

  // 退出登录
  const logout = () => {
    token.value = "";
    userInfo.value = {
      country: "",
      nickname: "",
      user_name: "",
      user_code: "",
      user_avatar: "",
      invitation_code: "",
      real_name_status: "",
      phone: "",
      email: "",
    };
    removeToken();
    uni.removeStorageSync("userInfo");
  };

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo };
    uni.setStorageSync("userInfo", userInfo.value);
  };

  // 初始化用户信息（从本地存储恢复）
  const initUserInfo = () => {
    const storedToken = getToken();
    const storedUserInfo = uni.getStorageSync("userInfo");

    if (storedToken) {
      token.value = storedToken;
    } else {
      token.value = "";
    }

    if (storedUserInfo) {
      userInfo.value = storedUserInfo;
    } else {
      // 重置用户信息为默认值
      userInfo.value = {
        country: "",
        nickname: "",
        user_name: "",
        user_code: "",
        user_avatar: "",
        invitation_code: "",
        real_name_status: null,
        phone: "",
        email: "",
      };
    }
  };

  // 检查登录状态
  const checkLoginStatus = () => {
    const storedToken = getToken();
    if (!storedToken) {
      logout();
      return false;
    }
    // 同步token状态
    if (token.value !== storedToken) {
      token.value = storedToken;
    }
    return true;
  };

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    isAuthentication,
    // 方法
    login,
    loginWithSms,
    sendSmsCode,
    logout,
    updateUserInfo,
    initUserInfo,
    checkLoginStatus,
    getUserInfo,
    editUserInfo,
    register,
  };
});
